package com.real8.romemp.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class QuestionAndAnswerViewImpl extends Composite implements
		QuestionAndAnswerView {

	private static QuestionAndAnswerViewImplUiBinder uiBinder = GWT
			.create(QuestionAndAnswerViewImplUiBinder.class);

	interface QuestionAndAnswerViewImplUiBinder extends
			UiBinder<Widget, QuestionAndAnswerViewImpl> {
	}

	private Presenter presenter;

	@UiField
	SpanElement questionSpan;
	@UiField
	TextBox answerTextBox;
	@UiField
	Label answerValidationLabel;

	public QuestionAndAnswerViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public void showQuestion(String question) {
		questionSpan.setInnerText(question);
		answerTextBox.setText("");
		answerValidationLabel.setVisible(false);
		this.setVisible(true);
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			@Override
			public void execute() {
				answerTextBox.setFocus(true);
			}
		});
	}

	@UiHandler("answerTextBox")
	void onKeyPress(KeyPressEvent e) {
		// check for digit || backspace || return
		char charCode = e.getCharCode();
		int keyCode = e.getNativeEvent().getKeyCode();
		if (!Character.isDigit(charCode) && !(keyCode == 8) && !(keyCode == 13)) {
			// invalid input
			answerTextBox.cancelKey();
			answerValidationLabel.setVisible(true);
		} else {
			// valid input
			answerValidationLabel.setVisible(false);

			// check for return
			if (keyCode == 13) {
				try {
					int allocation = Integer.parseInt(answerTextBox.getText());

					presenter.onAnswer(allocation);
				} catch (NumberFormatException e1) {
					answerValidationLabel.setVisible(true);
				}
			}
		}
	}
}
